const { sqlPromise } = require("../db/sqlPromise");
const bcrypt = require("bcryptjs");
exports.getUserInfo = async (req, res) => {
  let sql =
    "select username,nickname,email,user_pic from ev_users where id = ?";
  let results = await sqlPromise(sql, [req.user.id]);
  console.log(results);
  if (results.length != 1)
    return res.send({ status: 1, message: "获取用户失败" });
  res.send({
    status: 0,
    message: "获取用户信息成功!",
    data: results[0],
  });
};

exports.updateUserInfo = async (req, res) => {
  //   let id = req.user.id;
  let userinfo = req.body;
  //   UPDATE node_user SET uname='张胜男' WHERE id=7
  let sql = "UPDATE ev_users SET nickname=?,email=? WHERE id=?";
  let results = await sqlPromise(sql, [
    userinfo.nickname,
    userinfo.email,
    req.user.id,
  ]);
  if (results.affectedRows != 1) {
    return res.send({ status: 1, msg: "更新用户信息失败" });
  }
  res.send({ status: 0, msg: "更新用户信息成功" });
};

exports.updatePassword = async (req, res) => {
  let user_sql = "select * from ev_users where id=?";
  let results = await sqlPromise(user_sql, [req.user.id]);
  if (!results.length)
    return res.send({ status: 1, msg: "该用户不存在 请注册" });

  const compareResult = bcrypt.compareSync(
    req.body.oldPwd,
    results[0].password
  );

  if (!compareResult) {
    return res.send({
      status: 1,
      msg: "输入的旧密码与原密码不同",
    });
  }
  let serectPwd = bcrypt.hashSync(req.body.newPwd, 10);
  let updateSql = "UPDATE ev_users SET password=? WHERE username=?";
  let updateRes = await sqlPromise(updateSql, [serectPwd, req.user.username]);
  if (updateRes.affectedRows != 1)
    return res.send({
      status: 1,
      msg: "更新密码失败",
    });
  res.send({
    status: 0,
    msg: "更新密码成功",
  });
};

exports.updateAvatar = async (req, res) => {
  const sql = "update ev_users set user_pic=? where id=?";
  let results = await sqlPromise(sql, [req.body.avatar, req.user.id]);
  if (results.affectedRows != 1)
    return res.send({
      status: 1,
      msg: "更新用户头像失败",
    });
  res.send({
    status: 0,
    msg: "更新用户头像成功",
  });
};
